<template>
  <BasicModal v-bind="$attrs" @register="registerModal" showFooter :title="getTitle" width="50%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema } from './menu.data';
import { BasicModal, useModalInner } from '@/components/Modal';

import { getMenuList } from '@/api/sys/menu';

import { useMessage } from '@/hooks/web/useMessage';

import { saveOrUpdateMenu } from '@/api/system/menu';

defineOptions({ name: 'MenuModal' });

const { createMessage: msg } = useMessage();

const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record,
    });
  }
  const treeData: any = await getMenuList();
  treeData.unshift({
    name: "父级",
    id: "0"
  })
  updateSchema({
    field: 'parentId',
    componentProps: { treeData },
  });
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    const res = await saveOrUpdateMenu(values, !!values.id);
    if (res.isSucceed) {
      msg.success('操作成功');
      closeModal();
      emit('success');
    }
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
